<?php

namespace fztadmin\modules\rbac\models\forms;

use common\models\db\AdminRole;
use common\models\db\AdminUserRole;
use common\Tools;
use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use yii\db\ActiveQuery;
use Exception;
use yii\db\Expression;
use yii\helpers\ArrayHelper;
use common\models\db\User as UserModel;

/**
* User represents the model behind the search form about `common\models\db\User`.
*/
class User extends UserModel
{
    public $has_is_checked_roles;

    public function getHasIsCheckedRoles()
    {
        $allRoles = AdminRole::getAllRoles();
        $hasRoles = $this->getAdminRoleIds();
        $hasIsCheckedRoles = [];
        foreach ($allRoles as $k => $v) {
            $isCheckedRole = $v->toArray();
            if (in_array($v->id, $hasRoles)){
                $isCheckedRole['isChecked'] = 1;
            }else{
                $isCheckedRole['isChecked'] = 0;
            }
            $hasIsCheckedRoles[] = $isCheckedRole;
        }
        return $hasIsCheckedRoles;
    }

    public function attributeLabels()
    {
        $attributeLabels = parent::attributeLabels();
        $attributeLabels = ArrayHelper::merge($attributeLabels, []);
        return $attributeLabels;
    }

    public function rules()
    {
        $rules = parent::rules();
        /*foreach ($rules as $k => $v) {
            if ($v[1] == 'required'){
                $rules[$k][0] = array_diff($rules[$k][0], ['created_at', 'updated_at', 'created_by', 'updated_by']);
            }
        }*/
        $rules = ArrayHelper::merge($rules, [
            ['has_is_checked_roles', 'safe'],
        ]);
        return $rules;
    }

    public function setRoles()
    {
        $newRoleIds = $this->has_is_checked_roles;
        $oldRoleIds = $this->getAdminRoleIds();
        $deleteIds = array_diff($oldRoleIds, $newRoleIds);
        $addIds = array_diff($newRoleIds, $oldRoleIds);
        $trans = Yii::$app->db->beginTransaction();
        try{
            foreach ($deleteIds as $k => $v) {
                AdminUserRole::findOne(['user_id' => $this->id, 'admin_role_id' => $v])->delete();
            }
            foreach ($addIds as $k => $v) {
                $adminUserRole = new AdminUserRole();
                $adminUserRole->user_id = $this->id;
                $adminUserRole->admin_role_id = $v;
                if (!$adminUserRole->save()){
                    throw new \yii\db\Exception("分配角色失败:".Tools::toJson($adminUserRole->errors));
                }
            }
            $trans->commit();
        }catch (Exception $e){
            $trans->rollBack();
            throw $e;
        }
    }
}
